#-*- coding:utf-8 -*-
import requests
from icalendar import Calendar, Event
import pytz
import datetime
import hashlib
import os
import re

#支持json
import json

#用于解决null等关键字未定义的问题
null = None
false = False
true = True

def sha1(data):
    return hashlib.sha1(data.encode('utf-8')).hexdigest()

# 在这里修改你开学第一周时间
yourstarttime = '2021-03-01'

def get_semesters_to_json():
        return [{"Name":"2020-2021学年第一学期","Code":"20201"},{"Name":"2020-2021学年第二学期","Code":"20202"},{"Name":"2021-2022学年第一个学期","Code":"20211"}]

def get_course_take_weeks(all_week):  # 返回课程上课的周
    course_take_weeks = []
    is_interval = 0
    if '单周' in all_week:
        is_interval = 1
    elif '双周' in all_week:
        is_interval = 2
    match_object = re.match(r'(\d+)-(\d+)', all_week)
    if match_object:
        start_week = int(match_object.group(1))
        end_week = int(match_object.group(2))
        for i in range(start_week, end_week + 1):
            if is_interval == 0 or (is_interval == 1 and i % 2 != 0) or (is_interval == 2 and i % 2 == 0):
                course_take_weeks.append(i)
    return course_take_weeks


def get_course_date(first_day_date_str, course_in_day_of_week, which_week):  # 返回上课的日期
    first_day_date = datetime.datetime.strptime(
        first_day_date_str, r'%Y-%m-%d')
    return first_day_date + datetime.timedelta(days=(which_week - 1) * 7 + (course_in_day_of_week - 1))


def get_course_take_time(course_time):  # 返回上课时间
    course_time_table = {'12': [[8, 0, 0], [9, 35, 0]],
                         '34': [[10, 5, 0], [11, 40, 0]],
                         '56': [[14, 0, 0], [15, 35, 0]],
                         '78': [[15, 55, 0], [17, 30, 0]],
                         '910': [[19, 0, 0], [20, 35, 0]]}
    return course_time_table[course_time][0], course_time_table[course_time][1]


def main():
    time_zone = pytz.timezone('Asia/Shanghai')
    first_day_date_str = yourstarttime
    schedule_json = yourjson
    if schedule_json == -1:
        print('yourjson 没填')
        exit(1)
    name = schedule_json['Name']
    class_name = schedule_json['className']
    courses = schedule_json['courses']
    calendar = Calendar()
    calendar.add('prodid', '-//My calendar product//mxm.dk//')
    calendar.add('version', '2.0')
    for course in courses:
        course_in_day_of_week = int(course['couDayTime'])  # 课程在星期几
        course_take_weeks = get_course_take_weeks(course['allWeek'])
        course_begin_time, course_end_time = get_course_take_time(course['coudeTime'])
        for week in course_take_weeks:
            course_date = get_course_date(first_day_date_str, course_in_day_of_week, week)
            event = Event()
            event.add('summary', course['couName'])
            event.add('dtstart',
                      datetime.datetime(course_date.year, course_date.month, course_date.day, course_begin_time[0],
                                        course_begin_time[1], course_begin_time[2], tzinfo=time_zone))
            event.add('dtend',
                      datetime.datetime(course_date.year, course_date.month, course_date.day, course_end_time[0],
                                        course_end_time[1], course_end_time[2], tzinfo=time_zone))
            event.add('dtstamp',
                      datetime.datetime(course_date.year, course_date.month, course_date.day, course_begin_time[0],
                                        course_begin_time[1], course_begin_time[2], tzinfo=time_zone))
            event.add('location', course['couRoom'])
            calendar.add_component(event)
    output_file_name = '{} - {}.ics'.format(class_name, name)
    output_file = open(output_file_name, 'wb')
    output_file.write(calendar.to_ical())
    output_file.close()
    print('Success write your calendar to', output_file_name)


if __name__ == '__main__':
    
    print("将复制的json完整复制，不要修改：")
    print("cmd命令行中粘贴请右击上方标题栏，编辑中可以粘贴！")
    yourjson = json.loads(input())
    os.system("cls")
    main()
    print("按任意键退出！")
    input()
